<?php
/**
 * UserIdentity class file.
 * ------------------------
 * verify password in DB and set the user states
 *
 * LICENSE: BSD
 * @copyright  2009 Gemisoft
 * @author Deepak Pradhan <deepak.pradhan@gemisoft.com>
 * @link http://grbac.gemisoft.com/
 * @version $Id$
 * @since 0.1
 */

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {
  private $_id;

  /**
   * Authenticates a user.
   * @return boolean whether authentication succeeds.
   * set add on varibales to user identity
   */
  public function authenticate() {
    $record = Users::model()->findByAttributes(array('username'=>$this->username));
    
    
    if($record===null) {
      $this->errorCode=self::ERROR_UNKNOWN_IDENTITY;
      return !$this->errorCode;
    }

    //if user is not active retirn with custom error code =9
    if(!$record->active) {
      $this->errorCode=9;
      return !$this->errorCode;
    }

    // make encryption password to compare
    $algo = ($record->algo) ? $record->algo : 'md5';
    $salt = date("YmdH",strtotime($record->created));

    if (!function_exists('hash')) {
      $this->password = md5($this->password.$salt);
    }
    else {
      $this->password = hash($algo, $this->password.$salt);
    }

    // comapre password
    if($record->password !== $this->password) {
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
      return !$this->errorCode;
    }

    // Set add-ons to user and update last login date
    $this->_id = $record->id;
    $this->setState('username' ,$record->username);
    $this->setState('namef'    ,$record->namef);
    $this->setState('namem'    ,$record->namem);
    $this->setState('namel'    ,$record->namel);
    $this->setState('email'    ,$record->email);
    $this->setState('lastlogin',$record->lastlogin);
    $this->setState('active'   ,$record->active);
    $this->setState('center'   ,$record->center);
    $this->getRoles($record->id);

    $record->lastlogin = new CDbExpression('NOW()');
    $record->saveAttributes(array('lastlogin'));
    $this->errorCode=self::ERROR_NONE;

    return !$this->errorCode;
  }

  public function getId() {
    return $this->_id;
  }

  private function getRoles($id) {
    $roles=Assignments::model()->findAll('userid='.$id);
    foreach ($roles as $role) {
      $this->setState("{$role->itemname}", 1);
    }
  }
}
